﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.IO;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Drawing.Imaging;
using System.Windows.Media.Imaging;
using System.Diagnostics;

namespace RichTextEditor
{
    /// <summary>
    /// Interaction logic for EditorWindow.xaml
    /// </summary>
    public partial class EditorWindow : Window
    {
        public string RichText { get; set; }
        public byte[] ImageData { get; set; }
        public event OnRichTextHandler OnRichText;
        public event OnImageHandler OnImage;
        public MemoryStream imageBuffer;

        public EditorWindow()
        {
            InitializeComponent();
        }

        private void cmdSave_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = true;
            this.Close();
        }

        private void cmdCancel_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
            this.Close();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Editor.Text = this.RichText;

            Editor.SetFocus();

            Editor.OnCtrlEnterKey = (sender2, e2) =>
            {
                this.DialogResult = true;
                this.Close();
            };

            if (this.ImageData != null)
            {
                var image = new BitmapImage();

                imageBuffer = new MemoryStream();

                imageBuffer.Write(this.ImageData, 0, this.ImageData.Length);

                imageBuffer.Seek(0, SeekOrigin.Begin);

                image.BeginInit();
                image.StreamSource = imageBuffer;
                image.EndInit();

                image.DownloadCompleted += (sender2, e2) =>
                {
                    imageBuffer.Close();
                    imageBuffer.Dispose();
                };

                Editor.Image = image;

                var streamTest = GetImageStream();
            }
        }

        private MemoryStream GetImageStream()
        {
            var stream = new MemoryStream();
            var image = Editor.Image;
            var writeableBitmap = new WriteableBitmap(image);
            var stride = (image.PixelWidth * image.Format.BitsPerPixel + 7) / 8;
            var pixels = new byte[image.PixelHeight * stride];
            var bitmap = new Bitmap(image.PixelWidth, image.PixelHeight);

            writeableBitmap.CopyPixels(pixels, stride, 0);
            var data = bitmap.LockBits(new Rectangle(0, 0, image.PixelWidth, image.PixelHeight), System.Drawing.Imaging.ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);

            Marshal.Copy(pixels, 0, data.Scan0, pixels.Length);

            bitmap.UnlockBits(data);

            bitmap.Save(stream, ImageFormat.Png);

            stream.Seek(0, SeekOrigin.Begin);

            return stream;
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (this.DialogResult == false)
            {
                this.ImageData = null;
                this.RichText = null;
            }
            else
            {
                if (Editor.Image != null)
                {
                    using (var stream = GetImageStream())
                    {
                        this.ImageData = new byte[stream.Length];

                        stream.Read(this.ImageData, 0, (int)stream.Length);

                        var imageData = this.ImageData;

                        OnImage(ref imageData);
                    }
                }
                else if (Editor.Text != null)
                {
                    this.RichText = Editor.Text;

                    OnRichText(this.RichText);
                }
            }
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter && e.KeyboardDevice.Modifiers == ModifierKeys.Control)
            {
                if (this.DialogResult != true)
                {
                    this.DialogResult = true;
                }

                this.Close();
            }

        }
    }
}
